<template>
  <div class="permission-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加权限
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="权限名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入权限名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="权限代码">
            <el-input
              v-model="searchForm.code"
              placeholder="请输入权限代码"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 权限树形表格 -->
      <el-table
        :data="permissionList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :default-expand-all="false"
      >
        <el-table-column prop="name" label="权限名称" min-width="200">
          <template #default="{ row }">
            <div class="permission-name">
              <el-icon v-if="row.icon" class="permission-icon">
                <component :is="iconComponents[row.icon]" />
              </el-icon>
              <span>{{ row.name }}</span>
              <el-tag v-if="row.type" :type="getPermissionTypeTag(row.type)" size="small">
                {{ getPermissionTypeLabel(row.type) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="权限代码" width="200" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip min-width="250" />
        <el-table-column prop="module" label="所属模块" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.module" type="info" size="small">
              {{ row.module }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="showEditDialog(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deletePermission(row)"
              :disabled="row.children && row.children.length > 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑权限对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="permissionForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限代码" prop="code">
              <el-input v-model="permissionForm.code" placeholder="请输入权限代码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限类型" prop="type">
              <el-select v-model="permissionForm.type" placeholder="请选择权限类型" style="width: 100%">
                <el-option label="模块权限" value="module" />
                <el-option label="页面权限" value="page" />
                <el-option label="操作权限" value="action" />
                <el-option label="数据权限" value="data" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属模块" prop="module">
              <el-select v-model="permissionForm.module" placeholder="请选择所属模块" style="width: 100%">
                <el-option label="系统管理" value="system" />
                <el-option label="CMDB资产管理" value="cmdb" />
                <el-option label="运维监控" value="monitor" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="父级权限" prop="parent_id">
          <el-tree-select
            v-model="permissionForm.parent_id"
            :data="parentPermissionOptions"
            :props="{ label: 'name', value: 'id', children: 'children' }"
            placeholder="请选择父级权限（可选）"
            clearable
            check-strictly
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-select v-model="permissionForm.icon" placeholder="请选择图标（可选）" style="width: 100%">
            <el-option label="仪表盘" value="HomeFilled">
              <el-icon><component :is="iconComponents.HomeFilled" /></el-icon> 仪表盘
            </el-option>
            <el-option label="设置" value="Setting">
              <el-icon><component :is="iconComponents.Setting" /></el-icon> 设置
            </el-option>
            <el-option label="用户" value="User">
              <el-icon><component :is="iconComponents.User" /></el-icon> 用户
            </el-option>
            <el-option label="盒子" value="Box">
              <el-icon><component :is="iconComponents.Box" /></el-icon> 盒子
            </el-option>
            <el-option label="监控" value="Monitor">
              <el-icon><component :is="iconComponents.Monitor" /></el-icon> 监控
            </el-option>
            <el-option label="CPU" value="Cpu">
              <el-icon><component :is="iconComponents.Cpu" /></el-icon> CPU
            </el-option>
            <el-option label="文档" value="Document">
              <el-icon><component :is="iconComponents.Document" /></el-icon> 文档
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="permissionForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入权限描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import {
  Plus,
  HomeFilled,
  Setting,
  User,
  Box,
  Monitor,
  Cpu,
  Document
} from '@element-plus/icons-vue'
import api from '@/utils/api'

// 注册图标组件
const iconComponents = {
  Plus,
  HomeFilled,
  Setting,
  User,
  Box,
  Monitor,
  Cpu,
  Document
}

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加权限')
const isEdit = ref(false)
const editPermissionId = ref(0)

const permissionList = ref([])
const formRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive({
  name: '',
  code: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 权限表单
const permissionForm = reactive({
  name: '',
  code: '',
  type: '',
  module: '',
  parent_id: null,
  icon: '',
  description: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限代码', trigger: 'blur' },
    { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '权限代码只能包含字母、数字和下划线，且不能以数字开头', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  module: [
    { required: true, message: '请选择所属模块', trigger: 'change' }
  ]
}

// 模拟权限数据（包含CMDB权限）
const mockPermissions = [
  // 系统管理模块
  {
    id: 1,
    name: '系统管理',
    code: 'system',
    type: 'module',
    module: 'system',
    icon: 'Setting',
    description: '系统管理模块权限',
    created_at: '2024-01-01 10:00:00',
    children: [
      {
        id: 11,
        name: '用户管理',
        code: 'system:user',
        type: 'page',
        module: 'system',
        icon: 'User',
        description: '用户管理页面权限',
        created_at: '2024-01-01 10:00:00',
        children: [
          {
            id: 111,
            name: '查看用户',
            code: 'system:user:view',
            type: 'action',
            module: 'system',
            description: '查看用户列表权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 112,
            name: '添加用户',
            code: 'system:user:add',
            type: 'action',
            module: 'system',
            description: '添加用户权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 113,
            name: '编辑用户',
            code: 'system:user:edit',
            type: 'action',
            module: 'system',
            description: '编辑用户权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 114,
            name: '删除用户',
            code: 'system:user:delete',
            type: 'action',
            module: 'system',
            description: '删除用户权限',
            created_at: '2024-01-01 10:00:00'
          }
        ]
      },
      {
        id: 12,
        name: '角色管理',
        code: 'system:role',
        type: 'page',
        module: 'system',
        description: '角色管理页面权限',
        created_at: '2024-01-01 10:00:00',
        children: [
          {
            id: 121,
            name: '查看角色',
            code: 'system:role:view',
            type: 'action',
            module: 'system',
            description: '查看角色列表权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 122,
            name: '添加角色',
            code: 'system:role:add',
            type: 'action',
            module: 'system',
            description: '添加角色权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 123,
            name: '编辑角色',
            code: 'system:role:edit',
            type: 'action',
            module: 'system',
            description: '编辑角色权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 124,
            name: '删除角色',
            code: 'system:role:delete',
            type: 'action',
            module: 'system',
            description: '删除角色权限',
            created_at: '2024-01-01 10:00:00'
          }
        ]
      },
      {
        id: 13,
        name: '权限管理',
        code: 'system:permission',
        type: 'page',
        module: 'system',
        description: '权限管理页面权限',
        created_at: '2024-01-01 10:00:00',
        children: [
          {
            id: 131,
            name: '查看权限',
            code: 'system:permission:view',
            type: 'action',
            module: 'system',
            description: '查看权限列表权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 132,
            name: '添加权限',
            code: 'system:permission:add',
            type: 'action',
            module: 'system',
            description: '添加权限权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 133,
            name: '编辑权限',
            code: 'system:permission:edit',
            type: 'action',
            module: 'system',
            description: '编辑权限权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 134,
            name: '删除权限',
            code: 'system:permission:delete',
            type: 'action',
            module: 'system',
            description: '删除权限权限',
            created_at: '2024-01-01 10:00:00'
          }
        ]
      },
      {
        id: 14,
        name: '菜单管理',
        code: 'system:menu',
        type: 'page',
        module: 'system',
        description: '菜单管理页面权限',
        created_at: '2024-01-01 10:00:00',
        children: [
          {
            id: 141,
            name: '查看菜单',
            code: 'system:menu:view',
            type: 'action',
            module: 'system',
            description: '查看菜单列表权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 142,
            name: '添加菜单',
            code: 'system:menu:add',
            type: 'action',
            module: 'system',
            description: '添加菜单权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 143,
            name: '编辑菜单',
            code: 'system:menu:edit',
            type: 'action',
            module: 'system',
            description: '编辑菜单权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 144,
            name: '删除菜单',
            code: 'system:menu:delete',
            type: 'action',
            module: 'system',
            description: '删除菜单权限',
            created_at: '2024-01-01 10:00:00'
          }
        ]
      }
    ]
  },
  // CMDB资产管理模块
  {
    id: 2,
    name: 'CMDB资产管理',
    code: 'cmdb',
    type: 'module',
    module: 'cmdb',
    icon: 'Box',
    description: 'CMDB资产管理模块权限',
    created_at: '2024-01-01 10:00:00',
    children: [
      {
        id: 21,
        name: '主机管理',
        code: 'cmdb:host',
        type: 'page',
        module: 'cmdb',
        icon: 'Monitor',
        description: '主机管理页面权限',
        created_at: '2024-01-01 10:00:00',
        children: [
          {
            id: 211,
            name: '查看主机',
            code: 'cmdb:host:view',
            type: 'action',
            module: 'cmdb',
            description: '查看主机列表权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 212,
            name: '添加主机',
            code: 'cmdb:host:add',
            type: 'action',
            module: 'cmdb',
            description: '添加主机权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 213,
            name: '编辑主机',
            code: 'cmdb:host:edit',
            type: 'action',
            module: 'cmdb',
            description: '编辑主机权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 214,
            name: '删除主机',
            code: 'cmdb:host:delete',
            type: 'action',
            module: 'cmdb',
            description: '删除主机权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 215,
            name: '连接主机',
            code: 'cmdb:host:connect',
            type: 'action',
            module: 'cmdb',
            description: '连接主机权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 216,
            name: '批量操作',
            code: 'cmdb:host:batch',
            type: 'action',
            module: 'cmdb',
            description: '主机批量操作权限',
            created_at: '2024-01-01 10:00:00'
          }
        ]
      },
      {
        id: 22,
        name: '主机组管理',
        code: 'cmdb:hostgroup',
        type: 'page',
        module: 'cmdb',
        description: '主机组管理页面权限',
        created_at: '2024-01-01 10:00:00',
        children: [
          {
            id: 221,
            name: '查看主机组',
            code: 'cmdb:hostgroup:view',
            type: 'action',
            module: 'cmdb',
            description: '查看主机组列表权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 222,
            name: '添加主机组',
            code: 'cmdb:hostgroup:add',
            type: 'action',
            module: 'cmdb',
            description: '添加主机组权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 223,
            name: '编辑主机组',
            code: 'cmdb:hostgroup:edit',
            type: 'action',
            module: 'cmdb',
            description: '编辑主机组权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 224,
            name: '删除主机组',
            code: 'cmdb:hostgroup:delete',
            type: 'action',
            module: 'cmdb',
            description: '删除主机组权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 225,
            name: '管理主机',
            code: 'cmdb:hostgroup:manage',
            type: 'action',
            module: 'cmdb',
            description: '管理主机组内主机权限',
            created_at: '2024-01-01 10:00:00'
          }
        ]
      },
      {
        id: 23,
        name: '环境管理',
        code: 'cmdb:environment',
        type: 'page',
        module: 'cmdb',
        description: '环境管理页面权限',
        created_at: '2024-01-01 10:00:00',
        children: [
          {
            id: 231,
            name: '查看环境',
            code: 'cmdb:environment:view',
            type: 'action',
            module: 'cmdb',
            description: '查看环境列表权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 232,
            name: '添加环境',
            code: 'cmdb:environment:add',
            type: 'action',
            module: 'cmdb',
            description: '添加环境权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 233,
            name: '编辑环境',
            code: 'cmdb:environment:edit',
            type: 'action',
            module: 'cmdb',
            description: '编辑环境权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 234,
            name: '删除环境',
            code: 'cmdb:environment:delete',
            type: 'action',
            module: 'cmdb',
            description: '删除环境权限',
            created_at: '2024-01-01 10:00:00'
          }
        ]
      },
      {
        id: 24,
        name: '主机类型管理',
        code: 'cmdb:hosttype',
        type: 'page',
        module: 'cmdb',
        icon: 'Cpu',
        description: '主机类型管理页面权限',
        created_at: '2024-01-01 10:00:00',
        children: [
          {
            id: 241,
            name: '查看主机类型',
            code: 'cmdb:hosttype:view',
            type: 'action',
            module: 'cmdb',
            description: '查看主机类型列表权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 242,
            name: '添加主机类型',
            code: 'cmdb:hosttype:add',
            type: 'action',
            module: 'cmdb',
            description: '添加主机类型权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 243,
            name: '编辑主机类型',
            code: 'cmdb:hosttype:edit',
            type: 'action',
            module: 'cmdb',
            description: '编辑主机类型权限',
            created_at: '2024-01-01 10:00:00'
          },
          {
            id: 244,
            name: '删除主机类型',
            code: 'cmdb:hosttype:delete',
            type: 'action',
            module: 'cmdb',
            description: '删除主机类型权限',
            created_at: '2024-01-01 10:00:00'
          }
        ]
      }
    ]
  },
  // 运维监控模块
  {
    id: 3,
    name: '运维监控',
    code: 'monitor',
    type: 'module',
    module: 'monitor',
    icon: 'Monitor',
    description: '运维监控模块权限',
    created_at: '2024-01-01 10:00:00',
    children: [
      {
        id: 31,
        name: '系统监控',
        code: 'monitor:system',
        type: 'page',
        module: 'monitor',
        icon: 'Cpu',
        description: '系统监控页面权限',
        created_at: '2024-01-01 10:00:00',
        children: [
          {
            id: 311,
            name: '查看监控',
            code: 'monitor:system:view',
            type: 'action',
            module: 'monitor',
            description: '查看系统监控权限',
            created_at: '2024-01-01 10:00:00'
          }
        ]
      },
      {
        id: 32,
        name: '日志管理',
        code: 'monitor:log',
        type: 'page',
        module: 'monitor',
        icon: 'Document',
        description: '日志管理页面权限',
        created_at: '2024-01-01 10:00:00',
        children: [
          {
            id: 321,
            name: '查看日志',
            code: 'monitor:log:view',
            type: 'action',
            module: 'monitor',
            description: '查看日志权限',
            created_at: '2024-01-01 10:00:00'
          }
        ]
      }
    ]
  }
]

// 获取权限类型标签类型
const getPermissionTypeTag = (type: string) => {
  const typeMap: Record<string, string> = {
    module: 'primary',
    page: 'success',
    action: 'warning',
    data: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取权限类型标签文本
const getPermissionTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    module: '模块',
    page: '页面',
    action: '操作',
    data: '数据'
  }
  return typeMap[type] || type
}

// 获取父级权限选项（用于下拉选择）
const parentPermissionOptions = computed(() => {
  const flattenPermissions = (permissions: any[], level = 0): any[] => {
    let result: any[] = []
    permissions.forEach(permission => {
      // 只有模块和页面权限可以作为父级
      if (permission.type === 'module' || permission.type === 'page') {
        result.push({
          id: permission.id,
          name: '  '.repeat(level) + permission.name,
          children: permission.children ? flattenPermissions(permission.children, level + 1) : []
        })
      }
    })
    return result
  }
  return flattenPermissions(mockPermissions)
})

// 获取权限列表
const fetchPermissionList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    // 使用模拟数据，支持搜索过滤
    let filteredData = [...mockPermissions]

    // 递归搜索函数
    const searchInPermissions = (permissions: any[], searchTerm: string): any[] => {
      return permissions.filter(permission => {
        const matchesSearch = !searchTerm ||
          permission.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
          permission.code.toLowerCase().includes(searchTerm.toLowerCase())

        if (matchesSearch) {
          return true
        }

        // 如果子权限匹配，也包含父权限
        if (permission.children && permission.children.length > 0) {
          const filteredChildren = searchInPermissions(permission.children, searchTerm)
          if (filteredChildren.length > 0) {
            permission.children = filteredChildren
            return true
          }
        }

        return false
      })
    }

    if (searchForm.name) {
      filteredData = searchInPermissions(filteredData, searchForm.name)
    }

    permissionList.value = filteredData
    pagination.total = filteredData.length

    // 这里应该调用实际的API
    // const response = await api.get('/rbac/permissions/', {
    //   params: {
    //     page: pagination.page,
    //     page_size: pagination.pageSize,
    //     ...searchForm
    //   }
    // })
    //
    // if (response.data.success) {
    //   permissionList.value = response.data.data.results
    //   pagination.total = response.data.data.total
    // }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchPermissionList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, { name: '', code: '' })
  pagination.page = 1
  fetchPermissionList()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchPermissionList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchPermissionList()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加权限'
  isEdit.value = false
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (permission: any) => {
  dialogTitle.value = '编辑权限'
  isEdit.value = true
  editPermissionId.value = permission.id

  Object.assign(permissionForm, {
    name: permission.name,
    code: permission.code,
    type: permission.type || '',
    module: permission.module || '',
    parent_id: permission.parent_id || null,
    icon: permission.icon || '',
    description: permission.description || ''
  })

  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(permissionForm, {
    name: '',
    code: '',
    type: '',
    module: '',
    parent_id: null,
    icon: '',
    description: ''
  })
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        let response
        if (isEdit.value) {
          response = await api.put(`/rbac/permissions/${editPermissionId.value}/`, permissionForm)
        } else {
          response = await api.post('/rbac/permissions/', permissionForm)
        }
        
        if (response.data.success) {
          ElMessage.success(`权限${isEdit.value ? '更新' : '创建'}成功`)
          dialogVisible.value = false
          fetchPermissionList()
        }
      } catch (error) {
        console.error('操作失败:', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 删除权限
const deletePermission = async (permission: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限 ${permission.name} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await api.delete(`/rbac/permissions/${permission.id}/`)
    if (response.data.success) {
      ElMessage.success('权限删除成功')
      fetchPermissionList()
    }
  } catch (error: any) {
    if (error.response?.status === 404) {
      ElMessage.error('权限不存在或已被删除')
    } else if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message !== 'cancel') {
      ElMessage.error('删除失败，请稍后重试')
    }
    // 刷新列表以确保数据同步
    fetchPermissionList()
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchPermissionList()
})
</script>

<style scoped>
.permission-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.02);
  border-radius: 8px;
  border: 1px solid rgba(120, 220, 255, 0.1);
}

.permission-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.permission-icon {
  color: var(--tech-accent-color);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
